﻿<template>
  <div>
    <el-dialog v-drag :title='dialogTitle' :visible.sync='dialogFormVisible' width='60%' @close="closeDialog">
      <el-form :model="ruleRefForm" ref="ruleRefForm" :rules='rulesRef'>
        <div class='page_tableContent'>
          <el-table :data='ruleRefForm.refInfoTable' style='width:100%' empty-text='暂无关联条件，请立即添加' border stripe class='editTable'>
            <el-table-column align='center' label='需关联字段' :render-header='handelHelp' label-class-name="本表中关联的字段">
              <template slot-scope='scope'>
              <el-form-item :prop="'refInfoTable[' + scope.$index + '].myCloumns'" :rules='rulesRef.myCloumns'>
                  <el-select v-model="scope.row.myCloumns" placeholder="请选择" filterable :disabled = showType>
                    <el-option v-for='(item, index) in myCloumnsList' :key='index'
                    :label="item.column_desc ? item.column_name + '(' + item.column_desc + ')' : item.column_name" :value="item.column_name"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align='center' label='关联的元数据表' :render-header='handelHelp' label-class-name="为需要关联字段选择可关联的元数据表">
              <template slot-scope='scope'>
                <el-form-item :prop="'refInfoTable[' + scope.$index + '].refTable'" :rules='rulesRef.refTable'>
                  <el-select v-model="scope.row.refTable" placeholder="请选择" filterable @change='changeRefTable(scope.row, 1)' :disabled = showType>
                    <el-option v-for='(item, index) in refTableList' :key='index'
                    :label="item.metadesc ? item.metadesc + '(' + item.metaname + ')' : item.metaname" :value="item.metaname"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align='center' label='关联的栏位' :render-header='handelHelp' label-class-name="从关联的元数据表中选择关联的栏位，关联的栏位不能为空">
              <template slot-scope='scope'>
                <el-form-item :prop="'refInfoTable[' + scope.$index + '].refCloums'" :rules='rulesRef.refCloums'>
                  <el-select v-model="scope.row.refCloums" placeholder="请选择" filterable :disabled = showType @focus='changeRefTable(scope.row, 0)'>
                    <el-option v-for='(item, index) in scope.row.selectOptions' :key='index'
                    :label="item.column_desc ? item.column_name + '(' + item.column_desc + ')' : item.column_name" :value="item.column_name"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label='操作' width='70'>
              <template slot-scope="scope">
                <el-button type='text' :disabled = showType @click="deleteRefItem(scope.$index)"><i class='iconfont icon-shanchu'></i>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 底部按钮和页码部分 -->
        <div class='page_bottomContent' v-if = '!showType'>
          <div class='page_btnsContent'>
            <el-form-item class='form_noLeftMargin'>
              <el-button type="primary" @click='addRefItem ()'>添加关联条件</el-button>
              <el-button type='primary' @click="resetSearchForm ('ruleRefForm')">取 消</el-button>
              <el-button type="primary" @click="submitSearchForm ('ruleRefForm')">确 定</el-button>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: ['showRefCloumsDialog', 'refCloumsList'],
  data () {
    return {
      dialogTitle: '',
      dialogFormVisible: false,
      // 本表的所有栏位
      myCloumnsList: [],
      // 可选择的所有的元数据表
      refTableList: [],
      // 查看形式
      showType: false,
      // 表单的信息
      ruleRefForm: {
        refInfoTable: [
          {
            myCloumns: '',
            refTable: '',
            refCloums: '',
            // 选择字段后出现的查询条件列表
            selectOptions: []
          }
        ]
      },
      rulesRef: {
        myCloumns: [
          {required: true, message: '栏位名称不能为空', trigger: 'change'}
        ],
        refTable: [
          {required: true, message: '关联的元数据表不能为空', trigger: 'change'}
        ],
        refCloums: [
          {required: true, message: '关联栏位名称不能为空', trigger: 'change'}
        ]
      }
    }
  },
  methods: {
    // 表头的提示信息
    handelHelp (h, {column}) {
      if (column.labelClassName) {
        return (
          <el-tooltip effect="dark" placement="top">
            <div slot='content'>{column.labelClassName}</div>
            <span>{column.label}</span>
          </el-tooltip>
        )
      }
    },
    // 初始化表格信息
    initTable () {
      this.getMyCloumns()
      this.ruleRefForm.refInfoTable = []
      if (this.refCloumsList.showType === 'edit') {
        this.dialogTitle = '设置' + this.refCloumsList.myMetaName + '关联条件'
        this.showType = false
      } else {
        this.dialogTitle = '查看' + this.refCloumsList.myMetaName + '关联条件'
        this.showType = true
      }
      // 当有关联条件时
      if (this.refCloumsList.ref_key) {
        let refKey = JSON.parse(this.refCloumsList.ref_key)
        for (let key in refKey) {
          let fromIndex = refKey[key].indexOf('.') + 1
          let EndIndex = refKey[key].lastIndexOf('.')
          let objExam = {
            myCloumns: key,
            refTable: refKey[key].slice(fromIndex, EndIndex),
            refCloums: refKey[key].slice(EndIndex + 1),
            selectOptions: []
          }
          this.ruleRefForm.refInfoTable.push(objExam)
        }
      }
    },
    // 新增查询信息
    addRefItem () {
      this.ruleRefForm.refInfoTable.push({
        myCloumns: '',
        refTable: '',
        refCloums: '',
        // 选择字段后出现的查询条件列表
        selectOptions: []
      })
    },
    // 关联的表格改变时
    changeRefTable (row, type) {
      if (type) {
        row.refCloums = ''
      }
      row.selectOptions = []
      // 获取关联的表格对应的栏位信息
      if (row.refTable) {
        this.refTableList.forEach(val => {
          if (val.metaname === row.refTable) {
            this.$set(row, 'selectOptions', val.columns)
          }
        })
      }
    },
    // 获取本表的字段以及可关联的表
    getMyCloumns () {
      this.myCloumnsList = []
      this.refTableList = []
      this.refCloumsList.totalTable.forEach(val => {
        if (val.metauid === this.refCloumsList.myMetaUid) {
          this.myCloumnsList = val.columns
        }
        for (let tableUid of this.refCloumsList.refTableUid) {
          if (val.metauid === tableUid) {
            this.refTableList.push(val)
          }
        }
      })
    },
    // 删除一条查询信息
    deleteRefItem (index) {
      this.$confirm('此操作将永久删除该关联条件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--info'
      }).then(() => {
        this.ruleRefForm.refInfoTable.splice(index, 1)
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      }).catch(() => {})
    },
    // 点击取消按钮时
    resetSearchForm (forms) {
      this.$refs[forms].clearValidate()
      this.$emit('giveUpRefCloumns')
    },
    // 点击上部的X关闭弹窗时
    closeDialog () {
      this.$emit('giveUpRefCloumns')
      this.$refs.ruleRefForm.clearValidate()
    },
    // 点击确定提交的按钮时
    submitSearchForm (forms) {
      this.$refs[forms].validate((valid) => {
        if (valid) {
          let toParent = {
            index: this.refCloumsList.index,
            ref_key: ''
          }
          if (this.ruleRefForm.refInfoTable.length) {
            let objExam = {}
            this.ruleRefForm.refInfoTable.forEach(val => {
              objExam[val.myCloumns] = 'EXTEND_METADATA.' + val.refTable + '.' + val.refCloums
            })
            toParent.ref_key = JSON.stringify(objExam)
          }
          this.$emit('successRefCloumns', toParent)
        } else {
          return false
        }
      })
    }
  },
  watch: {
    showRefCloumsDialog: {
      handler: function (val, oldVal) {
        this.dialogFormVisible = val
        if (val) {
          this.initTable()
        }
      },
      deep: true
    }
  }
}
</script>
